package com.tools.scanner.camera

import android.hardware.Camera
import android.util.Log
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage
import java.nio.ByteBuffer

class ScanCodeHelper(private val mCallback: OnScanCallback) {
    private val mBarcodeScanner = BarcodeScanning.getClient()

    fun processImage(data: ByteArray, rotationDegrees: Int, camera: Camera) {
        val byteBuffer = ByteBuffer.wrap(data)
        val previewSize = try {
            camera.parameters.previewSize
        } catch (e: Exception) {
            return
        }

        val inputImage = InputImage.fromByteBuffer(
            byteBuffer,
            previewSize.width,
            previewSize.height,
            rotationDegrees,
            InputImage.IMAGE_FORMAT_NV21
        )

        mBarcodeScanner.process(inputImage).addOnSuccessListener { result ->
            if (result.isEmpty()) {
                mCallback.onScanCodeFail()
                return@addOnSuccessListener
            }
            mCallback.onScanCodeSuccess(result[0])
        }.addOnFailureListener {
            mCallback.onScanCodeFail()
        }
    }

    interface OnScanCallback {
        fun onScanCodeSuccess(barcode: Barcode)

        fun onScanCodeFail()
    }
}